import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import config, { handleMenus } from "@/config";

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  roles: [],
  userInfo: null,
  loginInfo: null,
  menusObj: {
    recommend: [], // 常用推荐
    project: [], // 项目
    state: [], // 阶段
    implement: [], // 实施
    system: [] // 系统管理
  },
  defaultImg: require('../../assets/login/user-default.png')
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_LOGIN_INFO: (state, loginInfo) => {
    // state.loginInfo = loginInfo
    state.menusObj["recommend"] = loginInfo.fast;
    if (loginInfo.projectType && loginInfo.projectType.length > 0) {
      state.menusObj["project"] = loginInfo.projectType[0].menus;
    }
    if (loginInfo.stageTypePlan && loginInfo.stageTypePlan.length > 0) {
      state.menusObj["state"] = loginInfo.stageTypePlan[0].menus;
    }
    if (
      loginInfo.stageTypeImplement &&
      loginInfo.stageTypeImplement.length > 0
    ) {
      state.menusObj["implement"] = loginInfo.stageTypeImplement[0].menus;
    }
    state.menusObj["system"] = loginInfo.system;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          commit("SET_TOKEN", getToken());
          localStorage.setItem("SET_LOGIN_INFO", JSON.stringify(response.data));
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // const { data } = {
      //     code: 1000,
      //     data: {
      //         roles: ['admin1'],
      //         introduction: 'I am a super administrator',
      //         avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      //         name: 'Super Admin'
      //     }
      // }

      // if (!data) {
      //     reject('Verification failed, please Login again.')
      // }

      // const { name, avatar, roles } = data

      // commit('SET_ROLES', roles)
      // commit('SET_NAME', name)
      // commit('SET_AVATAR', avatar)
      // console.log(data)
      // resolve(data)

      getInfo(state.token)
        .then(response => {
          let loginInfo = JSON.parse(localStorage.getItem("SET_LOGIN_INFO"));
          let menusArr = [];
          if (loginInfo) {
            commit("SET_LOGIN_INFO", loginInfo);
            for (const key in state.menusObj) {
              menusArr = menusArr.concat(handleMenus(state.menusObj[key]));
            }
            menusArr = menusArr.concat(
              config["twoPhaseYwArr"],
              config["threePhaseYwArr"],
              config["integrityArr"]
            );
          } else {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            localStorage.removeItem("SET_LOGIN_INFO");
            removeToken();
            resetRouter();
          }

          // response.data.roles = config.menus[response.data.role.extend]
          response.data.roles = menusArr;
          if(response.data.headPhoto){
            response.data.avatar = config.baseUrlImg + response.data.headPhoto;
          }else{
            response.data.avatar = state.defaultImg;
          }
          response.data.name = response.data.name;
          response.data.userInfo = response.data;

          const { data } = response;

          if (!data) {
            reject("Verification failed, please Login again.");
          }

          const { name, avatar, roles, userInfo } = data;

          commit("SET_ROLES", roles);
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_USERINFO", userInfo);

          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      localStorage.removeItem("SET_LOGIN_INFO");
      removeToken();
      resetRouter();
      resolve();
      // logout(state.token).then(() => {
      // }).catch(error => {
      //     reject(error)
      // })
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // 切换角色
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + "-token";

      commit("SET_TOKEN", token);
      setToken(token);

      const { roles } = await dispatch("getInfo");

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch("permission/generateRoutes", roles, {
        root: true
      });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

      // reset visited views and cached views
      dispatch("tagsView/delAllViews", null, { root: true });

      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};